<template>
  <div class="login-container">
    <van-nav-bar title="登录" class="my-nav-bar" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        required
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请输入手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        required
        label="验证码"
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          loading-text="加载中"
          loading-type="spinner"
          :loading="isloading"
          :disabled="isloading"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '../../api/login.js'
import { saveToken } from '../../utils/token'
export default {
  name: 'logim',
  data () {
    return {
      isloading: false,
      mobile: '15554555444',
      code: '246810'
    }
  },
  methods: {
    onSubmit (values) {
      // console.log('submit', values)
      this.isloading = true
      userLogin(values)
        .then(res => {
          saveToken(res.data.data)
          this.$toast.success(
            { message: '登陆成功', icon: 'gem' },
            setTimeout(() => {
              this.isloading = false
              const redirect = this.$route.query.redirect
              if (redirect) {
                return this.$router.push({
                  path: redirect
                })
              }
              this.$router.push({
                path: '/home'
              })
            }, 500)
          )
        })
        .catch(errRer => {
          this.$toast.fail(
            { message: '登陆失败', icon: 'eye' },
            setTimeout(() => {
              this.isloading = false
            }, 500)
          )
        })
    }
  }
}
</script>

<style lang="less">
.login-container {
  .my-nav-bar {
    background-color: #3196fa;
    .van-nav-bar__title.van-ellipsis {
      color: white;
    }
  }
}
</style>
